
from datetime import datetime
from h3yun.service.site_data_service import find_pss_site_mate_data
from h3yun.service.goods_service import find_pss_goods_mate_data
from h3yun.service import site_data_service, medical_goods_servce


# 这里查的是氚云的站点备案表
def get_site_dict():
    site_dict = {}
    site_list = site_data_service.find_site_info_data()
    for site in site_list:
        site_name = site['F0000011']
        site_code = site['F0000026']
        site_dict[site_name] = str(site_code)
    site_change_list = site_data_service.find_change_site_info_data()
    for site_change in site_change_list:
        site_name = site_change['F0000027']
        site_code = site_change['F0000026']
        site_dict[site_name] = str(site_code)
    return site_dict


# 把配送商的站点编码 替换 氚云上的站点编码
# F0000002 配送商站点编码  02023001(国药广西) 02093001(柳药)
# F0000005 医院编码（配送商备案）
# F0000004 医院编码（公司备案）
# F0000003 医院名称 （公司的）
def get_pss_site_to_h3yun_site_dict(pss_code):
    site_list = find_pss_site_mate_data()
    site_list = filter(lambda x: x.get('F0000002', '') == pss_code, site_list)
    site_code_dict = {}
    for site in site_list:
        site_code_dict[str(site.get('F0000005'))] = site
    return site_code_dict


# 把配送商的商品编码 替换 氚云上的站点编码
# F0000002 配送商站点编码  02023001(国药广西) 02093001(柳药)
# F0000005 产品编码（配送商备案）
# F0000004 产品编码（公司备案）
# F0000003 产品名称 (公司的)
def get_pss_goods_to_h3yun_site_dict(pss_code):
    goods_list = find_pss_goods_mate_data()
    goods_list = filter(lambda x: x.get('F0000002') == pss_code, goods_list)
    goods_code_dict = {}
    for goods in goods_list:
        goods_code_dict[str(goods.get('F0000005'))] = goods
    return goods_code_dict


#  F0000049 备案销售客户/医院名称编码
#  F0000051 销售终端医院编码
# D117400Fnczoagqa7nmbvn0erffeps704.F0000026 产品编码
# D117400Fnczoagqa7nmbvn0erffeps704.F0000023 生产厂家名称
# D117400Fnczoagqa7nmbvn0erffeps704.F0000045 终端医院供货价
# D117400Fnczoagqa7nmbvn0erffeps704.F0000006 产品名称
def mate_medical_goods(df, keys_dict=None):
    # 1. 先匹配 医疗器械销售信息备案
    medical_goods_list = medical_goods_servce.find_medical_goods_data()
    site_dict = get_site_dict()
    for index in range(len(df['产品编码(配送商的)'])):
        site_code = site_dict.get(df['配送商'][index], 0)
        # print(f"{df['配送商'][index]} {site_code}")
        for medical_goods in medical_goods_list:
            if medical_goods['Status'] != 1:
                continue
            #if df['配送商'][index] == '广西柳药集团股份有限公司':
               # print(f"{df['医院名称(公司内部的)'][index]} {df['医院编码(公司内部的)'][index]}")

            if ((medical_goods['F0000049'] == site_code or medical_goods['F0000051'] == medical_goods['F0000049'])
                    and medical_goods['F0000051'] == df['医院编码(公司内部的)'][index]):
                goods_list = medical_goods['D117400Fnczoagqa7nmbvn0erffeps704']
                goods_dict = make_list_to_dict(goods_list, 'F0000026')
                goods = goods_dict.get(df['产品编码(公司内部的)'][index], None)
                # if df['配送商'][index] == '广西柳药集团股份有限公司':
                #     print(df['产品编码(公司内部的)'][index])
                if goods is not None:
                    for key, value in keys_dict.items():
                        # df.loc[index, '生产厂家'] = goods['F0000023']
                        # df.loc[index, '单价'] = goods['F0000045']
                        df.loc[index, key] = goods[value]
                        # print(f"{df['配送商'][index]} {key}: {goods[value]}")
                    break


# F0000049 销售客户名称/医院编码
# F0000051 销售终端医院编码
#  D117400Fbslm7kwhysem74i3jdcu3zl47.F0000078 变更后-执行日期
# D117400Fbslm7kwhysem74i3jdcu3zl47.F0000026 产品编号
# D117400Fbslm7kwhysem74i3jdcu3zl47.F0000008 公司销售单价（元）
# D117400Fbslm7kwhysem74i3jdcu3zl47.F0000069 变更后终端医院供货价
def mate_change_medical_goods(df, keys_dict=None):
    medical_change_goods_list = medical_goods_servce.find_medical_changes_goods_data()
    site_dict = get_site_dict()
    for index in range(len(df['产品编码(配送商的)'])):
        site_code = site_dict.get(df['配送商'][index], 0)
        for medical_goods in medical_change_goods_list:
            if medical_goods['Status'] != 1:
                continue
            price_change_list = []
            if ((medical_goods['F0000049'] == site_code or medical_goods['F0000051'] == medical_goods['F0000049'])
                    and medical_goods['F0000051'] == df['医院编码(公司内部的)'][index]):
                goods_list = medical_goods['D117400Fbslm7kwhysem74i3jdcu3zl47']
                for goods in goods_list:
                    # 原始日期字符串
                    date_str = goods['F0000078']
                    # 解析原始日期字符串
                    date_obj = datetime.strptime(date_str, "%Y/%m/%d %H:%M:%S")
                    # 转换为所需格式
                    new_date_str = date_obj.strftime("%Y-%m-%d")
                    if goods['F0000026'] == df['产品编码(配送商的)'][index] and new_date_str <= df['出库时间'][index]:
                        temp = {
                            'date': new_date_str,
                        }
                        for key, value in keys_dict.items():
                            temp[key] = value
                        price_change_list.append(temp)
                if len(price_change_list) != 0:
                    sorted_PSD_list = sorted(price_change_list, key=lambda x: x['date'], reverse=True)
                    # df['单价'][index] = sorted_PSD_list[0]
                    for key, value in sorted_PSD_list[0].items():
                        if key != 'date':
                            df.loc[index, key] = value


def make_list_to_dict(goods_list, key):
    goods_dict = {}
    for goods in goods_list:
        goods_dict[str(goods[key])] = goods
    return goods_dict
